home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / vol_300 / 333_01 / awk.doc < prev    next >
Text File  |  1989-04-21  |  80KB  |  2,047 lines

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.                                gAWK Documentation
  8.                            Feb 10, 1989 - Bob Withers
  9.  
  10.  
  11.                                   INTRODUCTION
  12.  
  13.          This document is intended as a description of the AWK
  14.          language as implemented in gAWK, a public domain program
  15.          which originated with the GNU project.  It is not intended as
  16.          an all inclusive training document, please see the references
  17.          section for material that meets this need.
  18.  
  19.          AWK is a pattern matching language which may be used to
  20.          create programs which manipulate ASCII data files.  AWK
  21.          derives some of its features from SNOBOL and some from the
  22.          'C' language.
  23.  
  24.          The basic AWK program consists of a series of patterns and
  25.          associated actions.  Each input record is tested with each
  26.          pattern in the program and the actions associated with those
  27.          that match are executed.  The format for an AWK program is as
  28.          follows:
  29.  
  30.                   pattern         { action }
  31.                   pattern         { action }
  32.  
  33.          AWK input is generally processed by an "implicit input loop"
  34.          which was borrowed from the SNOBOL language.  AWK reads input
  35.          records from the specified files, breaks them into fields
  36.          based upon program controllable delimiters, and matches them
  37.          against the patterns in the AWK program.  Each pattern which
  38.          is TRUE for the current record has its associated action
  39.          statements executed.
  40.  
  41.          The fields created for each record are given special variable
  42.          names and may be used by the AWK program.  The special
  43.          variable $0 is used to reference the entire input record in
  44.          exactly the format it was read.  $1 refers to the first field
  45.          of the record, $2 the second, and so on.  For example,
  46.          suppose AWK was breaking fields apart based on a comma
  47.          delimiter.  The record:
  48.  
  49.               Now,is the, time, for all good men
  50.  
  51.          would be parsed as follows:
  52.  
  53.               $0 = "Now,is the, time, for all good men"
  54.               $1 = "Now"
  55.               $2 = "is the"
  56.               $3 = " time"
  57.               $4 = " for all good men"
  58.  
  59.          Special builtin AWK variables provide information about the
  60.          parsing of input lines and allow programs to override the
  61.  
  62.  
  63.  
  64.                           gAWK Documentation - Page 1
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
  73.          default processing.  After each input record is parsed into
  74.          fields the builtin variable NF is set to the number of fields
  75.          in the record.  In the above example NF would be set to 4.
  76.  
  77.          Two builtin variables control the way AWK parses input files
  78.          into records and fields.  The RS (Record Separator) builtin
  79.          variable is used by AWK to determine the delimiter for
  80.          records.  It may be set to any single character and is by
  81.          default set to the newline character ("\n").  The variable FS
  82.          (Field Separator) is used by AWK to determine how fields
  83.          within records are parsed.  Until recently FS was restricted
  84.          to a single character value also.  The current Unix version
  85.          of AWK (called nawk) has greatly enhanced the use of the FS
  86.          variable and these enhancements are supported in this version
  87.          of gAWK.  Rather than having FS represent a single character
  88.          field delimiter gAWK treats the contents of FS as a regular
  89.          expression.  The default value of FS in gAWK is "[ \t]+"
  90.          which means that fields are delimited by one or more blanks
  91.          or tabs (whitespace).  For most input files this default is
  92.          acceptable but both the FS and RS variables may be overridden
  93.          on either the AWK command line or within an AWK program.
  94.          More information is provided on both builtin variables and
  95.          regular expression later in this document.
  96.  
  97.                           AWK COMMAND LINE PARAMETERS
  98.  
  99.          The format of the AWK command line is as follows:
  100.  
  101.          AWK [-Ffs] [-Rrs] {"program" | -f progfile} [datfile ...]
  102.  
  103.          In the above command line brackets [ ] indicate and optional
  104.          argument and braces { } indicate a choice.
  105.  
  106.          The optional -F switch may be used from the command line to
  107.          override the default value of the FS builtin variable used to
  108.          parse input records into fields.  Under both MSDOS and OS/2
  109.          it is best to enclose the -F switch within double quotes if
  110.          it contains spaces or special characters.  For example to
  111.          parse input fields delimited by commas, semi-colons, and
  112.          colons one might code the -F switch as "-F[,;:]".
  113.  
  114.          The optional -R switch can be used to override the default
  115.          value for the RS builtin value.  If, for example, records are
  116.          to be delimited by an ampersand we could code the -R switch
  117.          as -R@.
  118.  
  119.          In general these command line switches are seldom used.  The
  120.          AWK language provides a means to override these variables
  121.          within the program and this is generally preferable to having
  122.          to remember to place the correct value on the command line.
  123.  
  124.          The actual statements of the AWK program are either supplied
  125.          on the command line or in an ASCII text file.  Providing the
  126.          AWK program on the command line is very popular in the Unix
  127.  
  128.  
  129.  
  130.                           gAWK Documentation - Page 2
  131.  
  132.  
  133.  
  134.  
  135.  
  136.  
  137.  
  138.  
  139.          environment, however, due to limitations of the command line
  140.          length under MSDOS and OS/2 it is practical only for very
  141.          short programs.  The following AWK program is supplied on the
  142.          command line and will print all the records in the file
  143.          MYFILE.DAT:
  144.  
  145.                   AWK "{ print $0 }" MYFILE.DAT
  146.  
  147.          It is more common for a program to be placed in an ASCII file
  148.          and specified on the command line via the -f switch.  The
  149.          recommended file name extension for these files is .AWK.  If
  150.          the above program were placed in the file MYPROG.AWK the
  151.          following command line would perform the same function as the
  152.          previous:
  153.  
  154.                    AWK -f myprog.awk myfile.dat
  155.  
  156.          The file(s) to be operated upon follow the switches and/or
  157.          AWK program on the command line.  Any number of files may be
  158.          specified and the normal MSDOS and OS/2 wildcard characters
  159.          may be used to include all matching file names.  The files
  160.          are processed in the order they are listed on the command
  161.          line.
  162.  
  163.          Special command line assignment statements may also be
  164.          included within the file name list of the command line.
  165.          These assignments take place in the order they appear on the
  166.          command line.  This feature may be used to provide
  167.          information to the AWK program relative to the files being
  168.          processed.  The format of these assignment statements are
  169.          variable=value and they are only restricted by the limits of
  170.          the command line length.  Again, if the value contains spaces
  171.          or special characters it is best to enclose the entire
  172.          assignment within double quotes to instruct the operating
  173.          system shell to parse it as a single argument to AWK.
  174.          Following is an example that uses the variable "p" to
  175.          instruct the AWK program of the number of the file currently
  176.          being processed:
  177.  
  178.          AWK -f myprog.awk p=1 file1.dat p=2 file2.dat p=3 file3.dat
  179.  
  180.          In the above execution the program MYPROG.AWK can refer to
  181.          the variable "p" to determine which file is being processed.
  182.          "p" is set to 1 before processing begins on FILE1.DAT.  It is
  183.          set to 2 when FILE1.DAT is closed and before FILE2.DAT is
  184.          opened, and so on.  There are better methods built into AWK
  185.          to determine this information but this example illustrates
  186.          the feature of command line assignments.
  187.  
  188.                               REGULAR EXPRESSIONS
  189.  
  190.          Many useful programs can be written with AWK without the use
  191.          of regular expressions, however, they are one of the most
  192.          powerful features of the language.  We will therefore take a
  193.  
  194.  
  195.  
  196.                           gAWK Documentation - Page 3
  197.  
  198.  
  199.  
  200.  
  201.  
  202.  
  203.  
  204.  
  205.          short detour into a discussion of regular expressions before
  206.          looking at the pattern matching features of AWK.
  207.  
  208.          A regular expression is a notation for specifying a pattern
  209.          for matching strings.  Regular expressions contain characters
  210.          which have special meaning and may be considered operators
  211.          just as plus (+) and minus (-) are arithmetic operators in
  212.          most languages.  These special characters are called
  213.          metacharacters.  Following are the regular expression
  214.          metacharacters supported by AWK:
  215.  
  216.                     \  ^  $  .  [  ]  |  (  )  *  +  ?
  217.  
  218.          A regular expression in AWK is surrounded by forward slash
  219.          characters and does not have to contain any metacharacters.
  220.          A regular expression without metacharacters matches itself.
  221.          The regular expression /ABC/ will match and string that
  222.          contains the substring "ABC".  Note that the match is case
  223.          sensitive and will not match the substring "ABc".  The
  224.          following table describes the format of regular expressions
  225.          where "c" is a non metacharacter, "m" is a metacharacter, and
  226.          "r" is a regular expression:
  227.  
  228.             c        Matches the non metacharacter c
  229.            \m        Treats metacharacter m as a literal character
  230.             ^        Forces match to the beginning of the string
  231.             $        Forces match to the end of the string
  232.             .        Matches and single character
  233.           [ccc]      Matches any single character in the class
  234.           [^ccc]     Matches any single character not in the class
  235.           [c-c]      Matches the range of characters specified
  236.           [^c-c]     Matches any character not in the range specified
  237.           r | r      Matches any string that matches either expression
  238.           (r1)(r2)   Matches string that matches r1 and is immediately
  239.                      followed by a string that matches r2
  240.           (r)*       Matches zero or more consecutive strings matched
  241.                      by r.  AWK matches the longest string possible.
  242.           (r)+       Matches one or more consecutive strings matched
  243.                      by r.  AWK matches the longest string possible.
  244.           (r)?       Matches zero or one occurrence of the string
  245.                      matched by r.
  246.  
  247.          As we've already seen a regular expression that contains no
  248.          metacharacters matches itself.  If this were the extent of
  249.          features offered, regular expressions would be of little use.
  250.          It is the metacharacters or "operators" which provide the
  251.          power of regular expressions.  We will look at each of the
  252.          metacharacters, describe how they are used, and give some
  253.          examples.
  254.  
  255.          The "literal" metacharacter \ is used to remove the special
  256.          properties associated with a metacharacter so that it can be
  257.          matched as a normal character.  To match a string containing
  258.          a dollar sign we could code a regular expression /\$/ which
  259.  
  260.  
  261.  
  262.                           gAWK Documentation - Page 4
  263.  
  264.  
  265.  
  266.  
  267.  
  268.  
  269.  
  270.  
  271.          would do the job.  Likewise to match the letter A followed by
  272.          a backslash followed by the letter B we could code the
  273.          regular expression /A\\B/.  The literal metacharacter is also
  274.          used to give special meaning to otherwise normal characters.
  275.          These special characters were inherited from the 'C' language
  276.          and should be familiar.  They are:
  277.  
  278.               \b        backspace character
  279.               \f        formfeed character
  280.               \n        newline character
  281.               \r        carriage return character
  282.               \t        tab character
  283.               \ddd      octal value ddd where ddd is 1 to 3 digits
  284.                         between 0 and 7
  285.  
  286.          The match beginning of line metacharacter forces a match to
  287.          occur at the beginning of a line.  The symbol used is the
  288.          caret (^).  To match all lines which begin with a Z we could
  289.          code /^Z/.  Note that the caret only has meaning at the
  290.          beginning of a regular expression (and within character
  291.          classes as we'll see shortly).  The use of a caret within a
  292.          regular expression is treated as a normal character although
  293.          is it prudent to use the backslash literal metacharacter
  294.          anyway if that is the intend.  For example, the regular
  295.          expression /AB^/ should match the same strings as /AB\^/.
  296.  
  297.          The match end of line ($) metacharacter is similar to the
  298.          caret operator only it forces the match to the end of the
  299.          line.  Matching all lines which end with a question mark
  300.          could be coded as /\?$/.  Note that since the question mark
  301.          is a metacharacter its use as a literal must be "quoted" by
  302.          the literal metacharacter.
  303.  
  304.          Lets look at some examples using both the caret and the
  305.          dollar sign:
  306.  
  307.               /^XX$/      Matches strings which consist of only the
  308.                           two characters "XX"
  309.               /^.$/       Matches strings which are exactly one
  310.                           character
  311.               /^\.$/      Matches strings which are exactly one
  312.                           character and are equal to a period.
  313.                           (compare this with the previous example)
  314.  
  315.          The period (.) metacharacter, as seen in the above examples
  316.          matches any single character.  Therefore the regular
  317.          expression /A..B/ will match any string which has a capital
  318.          letter A and a capital letter B separated by any two other
  319.          characters.
  320.  
  321.          The bracket metacharacters [ ] are used to define characters
  322.          classes.  A character class can be used to match a single
  323.          character but allows alternatives to be supplied.  To match
  324.          any string which contains the letter A or the letter B we
  325.  
  326.  
  327.  
  328.                           gAWK Documentation - Page 5
  329.  
  330.  
  331.  
  332.  
  333.  
  334.  
  335.  
  336.  
  337.          could code /[AB]/.  To match any string that start with an A
  338.          or a B we code /^[AB]/.  If a character class begins with a
  339.          caret the operation is negated, i.e. the expression matches
  340.          characters that are not part of the class.  To match strings
  341.          which begin with anything other than an A or a B we could
  342.          code /^[^AB]/.  Don't confuse the begin of line metacharacter
  343.          with the character class negation character.  A caret
  344.          appearing anywhere within a character class is treated as a
  345.          literal character, /[A^B]/ will match string containing
  346.          either an A, a B, or a caret.
  347.  
  348.          Character classes allow a range of characters to be specified
  349.          by using a dash to separate the first character of the range
  350.          from the last.  Matching a string containing any lower case
  351.          letter could be coded as /[a-z]/ which is much easier than
  352.          having to enumerate all twenty six letters.  Multiple ranges
  353.          may be specified and combined with single letter values.  The
  354.          regular expression /[A-CXYI-K]/ will match a string
  355.          containing any of the following characters A,B,C,X,Y,I,J,K.
  356.          Expressions containing ranges may also be negated as in
  357.          /[^ABJ-K]/.
  358.  
  359.          The next metacharacter is the alteration or "OR" operator.
  360.          This operator allows an expression to match if any of its
  361.          subexpressions match.  The expression /A|B/ will match any
  362.          string containing either A or B.
  363.  
  364.          Parenthesis are used to group expressions to override the
  365.          normal operator precedence.  For example the expression
  366.          /ABC|XYZ/ looks like it might match strings containing either
  367.          ABC or XYZ.  However, due to the higher precedence of the |
  368.          operator it actually matches strings containing either ABCYZ
  369.          or ABXYZ.  To match strings containing either ABC or XYZ we
  370.          must code the expression as /(ABC)|(XYZ)/.
  371.  
  372.          We will treat the last three metacharacters as a group and
  373.          label them the "repeat operators".  Technically they are
  374.          known as the closure operators and their function is to allow
  375.          a subexpression to be repeated.  The * metacharacter repeats
  376.          a subexpression zero or more times.  The expression /A*/
  377.          matches the strings "", "A", "AA", "AAA", and so on. Likewise
  378.          /AB*/ matches "A", "AB", "ABB", etc.  Parenthesis may be used
  379.          to repeat more than a single character as in /(AB)*/ which
  380.          would match "", "AB", "ABAB", etc.
  381.  
  382.          The + metacharacter is similar to the * but it will not match
  383.          the NUL string "" (zero repeats) like * does.  The expression
  384.          /[ABC]+/ will match one or more consecutive characters in the
  385.          set ABC as in "A", "B", "CA", CCCBA", etc.
  386.  
  387.          The final metacharacter is the question mark and is used to
  388.          match exactly zero or one occurrence of the expression.  The
  389.          expression /AB?/ will match "A" or "AB".
  390.  
  391.  
  392.  
  393.  
  394.                           gAWK Documentation - Page 6
  395.  
  396.  
  397.  
  398.  
  399.  
  400.  
  401.  
  402.  
  403.          In AWK all of the repeat metacharacters will match the
  404.          largest possible substring, therefore given the string
  405.          "AAAAAAAAAA" and the regular expression /A+/ the entire
  406.          string will be matched rather than just the first character.
  407.  
  408.                                     PATTERNS
  409.  
  410.          Patterns in AWK are used to select particular input records
  411.          for a specific type of processing.  They are conditional
  412.          expressions which cause their associated action to be
  413.          performed if they are TRUE.  Following are the types of
  414.          patterns supported:
  415.  
  416.               BEGIN          Special pattern which is performed before
  417.                              the first input file is opened.
  418.               END            Special pattern which is performed after
  419.                              the last input file has been processed.
  420.               expression     Action is executed for each input line
  421.                              where "expression" is TRUE.
  422.               /reg exp/      Action is executed for each input line
  423.                              that is matched by the regular
  424.                              expression.
  425.               compound pat   A compound pattern is comprised of
  426.                              several patterns connected by the boolean
  427.                              operators && (AND), || (OR), ! (NOT), and
  428.                              parentheses.
  429.               pat1, pat2     A range pattern matches each input line
  430.                              starting with one matched by "pat1" up to
  431.                              and including one matched by "pat2".
  432.               empty          The empty pattern consists of only an
  433.                              action.  The pattern is unconditionally
  434.                              TRUE and the action is executed for every
  435.                              input record.
  436.  
  437.          The BEGIN and END special patterns are not used to match
  438.          input lines but rather are used to perform program
  439.          initialization and termination.  The action associated with
  440.          the BEGIN pattern is executed before AWK reads any input
  441.          records.  It can be used to initialize variables, print
  442.          headings, or set AWK builtin variables which control input
  443.          and output field splitting.  The END special pattern is
  444.          matched after all input files have been processed.  It can be
  445.          used perform cleanup or print accumulated totals.  For
  446.          example, the following AWK program counts the number of input
  447.          lines and uses the END pattern to print out the result:
  448.  
  449.                       { ++cnt }
  450.  
  451.             END       { print cnt, "records were read" }
  452.  
  453.          The first pattern/action pair in this program adds one to the
  454.          variable "cnt" for each input record processed by AWK.  It
  455.          consists of only an action, making use of the "empty" pattern
  456.          to match all input records.  After all input records are
  457.  
  458.  
  459.  
  460.                           gAWK Documentation - Page 7
  461.  
  462.  
  463.  
  464.  
  465.  
  466.  
  467.  
  468.  
  469.          processed, the END pattern/action pair is executed and
  470.          prints the accumulated value of "cnt".
  471.  
  472.          The "expression" pattern is a conditional expression which,
  473.          if TRUE, will cause the action associated with it to be
  474.          executed.  AWK has a rich set of comparison operators which
  475.          may be used in conjunction with builtin variables, program
  476.          defined variables, and/or AWK field variables.  The following
  477.          table presents the comparison operators supported by this
  478.          version of AWK:
  479.  
  480.                        <         Less than
  481.                        <=        Less than or equal to
  482.                        ==        Equal to
  483.                        !=        Not equal to
  484.                        >=        Greater than or equal to
  485.                        >         Greater than
  486.                        ~         Matched by
  487.                        !~        Not matched by
  488.  
  489.          If we wanted to process input records which contained more
  490.          than 5 fields we could make use of the NF builtin variable to
  491.          construct a pattern that would match these records: NF > 5.
  492.          AWK conditional expressions can also contain arithmetic or
  493.          string operators.  If our input data had employee hourly rate
  494.          in field #1 and number of hours worked in field #3 then the
  495.          pattern $1 * $3 > 100 would select input records where the
  496.          employee's pay is greater than $100.00.
  497.  
  498.          Most of the comparison operators used in AWK are similar to
  499.          those available in other high level languages and should be
  500.          readily understood.  The match operators found in AWK are not
  501.          quite as common and deserve some explanation.  These
  502.          operators are used to match an expression against a regular
  503.          expression.  The tilde (~) is the match operator and can be
  504.          negated by use of the exclamation mark (!~).  For example, if
  505.          we wanted to print records where the 5th field contained the
  506.          string "Jones" we could code the following program:
  507.  
  508.               $5 ~ /Jones/       { print $0 }
  509.  
  510.          This program will use the literal regular expression
  511.          specified as the second argument of the match operator to
  512.          compare against the expression which is the left argument.
  513.          If a match is found the pattern is TRUE and the action is
  514.          executed.  Likewise printing all records which did not
  515.          contain the string "Jones" in field 5 would be coded as:
  516.  
  517.               $5 !~ /Jones/       { print $0 }
  518.  
  519.          Note that the match operation is a regular expression search.
  520.          If field five contained the string "Where is Jones?" the
  521.          regular expression /Jones/ would match it.  If an exact match
  522.          is desired use the equality operator as in:
  523.  
  524.  
  525.  
  526.                           gAWK Documentation - Page 8
  527.  
  528.  
  529.  
  530.  
  531.  
  532.  
  533.  
  534.  
  535.               $5 == "Jones"         { print $0 }
  536.  
  537.          The match operator supports a new AWK feature called "dynamic
  538.          regular expressions".  This feature allows the value of an
  539.          expression to be compiled as a regular expression and used as
  540.          such.  The value of this expression must be a valid regular
  541.          expression or a run time error will occur.  Consider the
  542.          pattern "$1 ~ $5" which instructs AWK to treat the value of
  543.          field #5 as a regular expression and use it to match the
  544.          contents of field #1.  For each input record field #5 could
  545.          be a different regular expression.  Our program to search for
  546.          the string "Jones" in field #5 could be coded as:
  547.  
  548.               BEGIN        { str = "Jones" }
  549.  
  550.               $5 ~ str     { print $0 }
  551.  
  552.          Use of dynamic regular expressions requires AWK to syntax
  553.          check and compile the expression each time it is used.  For
  554.          this reason dynamic regular expressions are not as efficient
  555.          as literal regular expressions which are checked and compiled
  556.          only once.  They are however very powerful and are well worth
  557.          the slight performance degradation if your application needs
  558.          them.
  559.  
  560.          There is a case of regular expression matching which occurs
  561.          so frequently that AWK provides a special shorthand notation.
  562.          The pattern "$0 ~ /Jones/" will match the regular expression
  563.          against the entire input record and evaluate as TRUE if there
  564.          is a match.  This format of the match operator can be
  565.          shortened to simply specifying the regular expression.  The
  566.          following program will print all records which contain the
  567.          string "Jones".
  568.  
  569.               /Jones/       { print $0 }
  570.  
  571.          Compound Patterns
  572.  
  573.          A compound pattern is an expression which uses logical
  574.          operators to combine other patterns.  The available logical
  575.          operators are AND (&&), OR (||), and NOT (!).
  576.  
  577.               $1 == "Jones" && NF > 10
  578.  
  579.          The above program will print each input record where the
  580.          first field is equal to the string "Jones" AND the number of
  581.          fields in the record is greater than ten.  Note that we have
  582.          omitted the action portion of the program.  If a pattern is
  583.          present the action may be omitted and will perform the
  584.          default action which is equivalent to { print $0 }.
  585.  
  586.               $1 == "Jones" || !(NF > 10)
  587.  
  588.          The above program will print all input records where the
  589.  
  590.  
  591.  
  592.                           gAWK Documentation - Page 9
  593.  
  594.  
  595.  
  596.  
  597.  
  598.  
  599.  
  600.  
  601.          first field is equal to the string "Jones" OR the number of
  602.          fields in the record is less than or equal to ten (take a
  603.          good look at it).
  604.  
  605.          Range Pattern
  606.  
  607.          The range pattern is a special construct which can be used to
  608.          match a series of input records.  The format is "pat1, pat2"
  609.          where pat1 and pat2 are regular expressions.  The pattern
  610.          will return TRUE when pat1 matches an input line and continue
  611.          to be TRUE up to (and including) an input line which matches
  612.          pat2.  For example:
  613.  
  614.               /Jones/, /Sampson/
  615.  
  616.          This program will print all input records beginning with one
  617.          matching the string "Jones" and continuing up to and
  618.          including a record that matches "Sampson".
  619.  
  620.          Summary of Patterns
  621.  
  622.               Pattern         Example               Matches
  623.  
  624.               BEGIN           BEGIN        Before any input is read
  625.  
  626.               END             END          After all input has been
  627.                                            read
  628.  
  629.               expression      $1 > 50      Lines with the first field
  630.                                            greater than 50
  631.  
  632.               matching        /Jones/      Lines that contain the
  633.                                            substring "Jones"
  634.  
  635.               compound        $1 < 5 && $1 > 0
  636.                                            Lines where the first field
  637.                                            is between 1 and 4
  638.  
  639.               range           NR == 1, NR == 20
  640.                                            The first 20 input records
  641.  
  642.                                     ACTIONS
  643.  
  644.          The action portion of an AWK program defines the statements
  645.          to be executed with a pattern associated with them is found
  646.          to be TRUE for the current input record.  As we've seen the
  647.          actions portion can be omitted in which case the default
  648.          action of printing the matching record is performed.  The
  649.          pattern portion of a statement may also be omitted which
  650.          creates a pattern that will match all input records.
  651.          However, both the pattern and action cannot be omitted,
  652.          either one or both must be present.
  653.  
  654.          The statements supported by AWK in the actions section are
  655.  
  656.  
  657.  
  658.                           gAWK Documentation - Page 10
  659.  
  660.  
  661.  
  662.  
  663.  
  664.  
  665.  
  666.  
  667.          similar to the constructs of the 'C' Language.  Following are
  668.          the allowable statements, capital letters indicate portions
  669.          of the statement which includes variable information:
  670.  
  671.               print EXPRESSION-LIST
  672.               printf(FORMAT, EXPRESSION-LIST)
  673.               if (EXPRESSION) STATEMENT
  674.               if (EXPRESSION) STATEMENT else STATEMENT
  675.               while (EXPRESSION) STATEMENT
  676.               do STATEMENT while (EXPRESSION)
  677.               for (EXPRESSION; EXPRESSION; EXPRESSION) STATEMENT
  678.               for (VARIABLE in ARRAY) STATEMENT
  679.               delete ARRAY-ELEMENT
  680.               break
  681.               continue
  682.               next
  683.               exit
  684.               { STATEMENTS }
  685.               VARIABLE = EXPRESSION
  686.  
  687.          Expressions
  688.  
  689.          Expressions in AWK can consist of constants, variables,
  690.          builtin variables, field variables, arithmetic expressions,
  691.          string expressions, conditional expressions, relational
  692.          expressions, builtin functions, or user defined functions.
  693.          We will look at each of these in turn.
  694.  
  695.          Expressions - Constants
  696.  
  697.          AWK supports two data types which are NUMBER and STRING.
  698.          String constants are written surrounded by double quotes and
  699.          may contain "escape characters" as used in 'C' Language
  700.          strings.  For example, to create a string literal which
  701.          contains the single character double quote we would code
  702.          "\"".  Other examples of string constants are "Jones",
  703.          "Hello, World", and "" which is the NUL string.
  704.  
  705.          Number constants are real numbers and are written without
  706.          quotes.  Numbers may be written as integers (556), decimal
  707.          numbers (5.17), or exponential notation (5.17E-2).  All
  708.          numbers are stored in floating point which, in this
  709.          implementation, uses the 'C' type double.
  710.  
  711.          Expressions - Variables
  712.  
  713.          User defined variables in AWK are created when they are first
  714.          referenced.  The programmer does not need to specify the type
  715.          of data the variable will store, AWK infers this from the
  716.          operations performed on the variable.  In fact the type of
  717.          data may change during the execution of the program and AWK
  718.          will convert the current contents of the variable to the
  719.          required type.  All variables are created empty.  In the case
  720.          of string variables they contain the NUL string and in the
  721.  
  722.  
  723.  
  724.                           gAWK Documentation - Page 11
  725.  
  726.  
  727.  
  728.  
  729.  
  730.  
  731.  
  732.  
  733.          case of number variables they contain the number zero.
  734.  
  735.          Each user defined variable is composed of letters, numbers,
  736.          and underscores and must not begin with a number.  Examples
  737.          are: total_count, sum, and my_var.
  738.  
  739.          Expressions - Builtin Variables
  740.  
  741.          AWK contains a number of builtin variables which may be used
  742.          to obtain information and/or control the operation of reading
  743.          and splitting fields.  All builtin variable names are spelled
  744.          with all capital letters.  Following is a list of supported
  745.          builtin variables:
  746.  
  747.               Variable                    Meaning
  748.  
  749.               ARGC            Number of command line arguments
  750.               ARGV            Array of command line arguments
  751.               FILENAME        Name of the current input file
  752.               FNR             Record number within the current file
  753.               FS              Input field separator (reg exp)
  754.               NF              Number of fields in the current record
  755.               NR              Record number of current record relative
  756.                               to start of execution
  757.               OFMT            Output format for numbers
  758.               OFS             Output field separator (string)
  759.               ORS             Output record separator
  760.               RLENGTH         Length of string matched by match()
  761.                               function
  762.               RS              Input record separator
  763.               RSTART          Start of string matched by match()
  764.                               function
  765.               SUBSEP          Subscript separator
  766.  
  767.          Following are the default values of these builtin variables:
  768.  
  769.                        Variable        Default
  770.  
  771.                        ARGC            Varies
  772.                        ARGV            Varies
  773.                        FILENAME        Varies
  774.                        FNR             Varies
  775.                        FS              "[ \t]+"
  776.                        NF              Varies
  777.                        NR              Varies
  778.                        OFMT            "%.6g"
  779.                        OFS             " "
  780.                        ORS             "\n"
  781.                        RLENGTH         0
  782.                        RS              "\n"
  783.                        RSTART          0
  784.                        SUBSEP          "\034"
  785.  
  786.          The builtin variables may be used just like user defined
  787.  
  788.  
  789.  
  790.                           gAWK Documentation - Page 12
  791.  
  792.  
  793.  
  794.  
  795.  
  796.  
  797.  
  798.  
  799.          variables.  For example, the following program will count the
  800.          number of input files and display this value and the end of
  801.          processing:
  802.  
  803.               prev != FILENAME   { ++no_files; prev = FILENAME }
  804.  
  805.               END                { print no_files, "file(s) input" }
  806.  
  807.          The user defined variable "prev" is created and initialized
  808.          to the NUL string and will therefore not be equal to the
  809.          first filename processed.  When this happen the variable
  810.          "no_files" is incremented and the value of "prev" is set
  811.          equal to the current filename.  At the end of input the
  812.          number of different files encountered is displayed.
  813.  
  814.          Expressions - Field Variables
  815.  
  816.          As discussed previously, AWK splits input records into fields
  817.          based on the regular expression contained in the builtin
  818.          variable FS.  These fields may be accessed or modified by the
  819.          AWK program by field number.  Fields are numbered beginning
  820.          from one (1).  The dollars ($) specifier is used to inform
  821.          AWK that an expression refers to a field.  For example, $1
  822.          refers to the first field in a record and $5 refers to the
  823.          fifth field.  The special field variable $0 is used to refer
  824.          to the entire input record just as it was read in by AWK.
  825.  
  826.          The expressions used to specify field variables do not need
  827.          to be numeric constants but can be any numeric expression.
  828.          Given that the builtin variable NF contains the number of
  829.          fields in the current records the variable $(NF - 1) refers
  830.          to the next to the last field.  Assume that an AWK program
  831.          was to print out the value of a single field for each input
  832.          record and that the number of the field to be printed was
  833.          contained in the first field of each record.  The following
  834.          AWK program would meet this specification:
  835.  
  836.                            { print $($1) }
  837.  
  838.          This version of AWK permits assignments to field variables.
  839.          If a single field is assigned a new value the contents of the
  840.          $0 variable are modified accordingly.  If a new value is
  841.          assigned to the $0 variable all field variables are
  842.          recalculated and a new value is assigned to NF.
  843.  
  844.          Expressions - Arithmetic Expressions
  845.  
  846.          AWK provides the usual arithmetic operators which may be used
  847.          to calculate numeric results.  All Arithmetic is performed in
  848.          floating point using double precision storage.  Following are
  849.          the individual operators supported:
  850.  
  851.  
  852.  
  853.  
  854.  
  855.  
  856.                           gAWK Documentation - Page 13
  857.  
  858.  
  859.  
  860.  
  861.  
  862.  
  863.  
  864.  
  865.  
  866.  
  867.            Operator     Function                Example
  868.  
  869.               +         Addition                $1 + $2
  870.               -         Subtraction             total + $4
  871.               -         Unary minus             -total
  872.               *         Multiplication          x * y
  873.               /         Division                $1 / x
  874.               %         Modulo (remainder)      x % y
  875.               ^         Exponentiation          $1 ^ 5
  876.               ++        Pre/Post increment      ++x or x++
  877.               --        Pre/Post decrement      --x or x--
  878.  
  879.          Expressions - String Expressions
  880.  
  881.          There is only one string operator supported by AWK.  It is
  882.          concatenation and is represented by spaces between variables
  883.          and/or constants.  The following program assigns some
  884.          constants to string variables and the concatenates them into
  885.          a single variable:
  886.  
  887.               BEGIN     {   x = "String 1"; y = "String 2"
  888.                             z = "(" x ":" y ")"
  889.                             print z
  890.                             exit
  891.                         }
  892.  
  893.          The output of this program will be:
  894.  
  895.               (String 1:String 2)
  896.  
  897.          While discussing string expressions seems like a good
  898.          opportunity to bring up AWK's use of dynamic regular
  899.          expression.  A dynamic regular expression in AWK is simply a
  900.          string variable which is treated as a normal regular
  901.          expression.  Strings which contain valid regular expressions
  902.          can be used anywhere that a literal regular expression can be
  903.          used.  For example the following program makes use of a
  904.          dynamic regular expression to print input which consist
  905.          solely of integer numbers:
  906.  
  907.               BEGIN      { num = "^[0-9]$" }
  908.  
  909.               $0 ~ num
  910.  
  911.          Notice that the action portion of the second rule of this
  912.          program is missing.  A missing action performs the default
  913.          action of printing the input record when the pattern is TRUE.
  914.  
  915.          The astute reader will have observed that AWK's builtin
  916.          variable FS is nothing more than a dynamic regular expression
  917.          which is used to delimit fields within input records.
  918.  
  919.  
  920.  
  921.  
  922.                           gAWK Documentation - Page 14
  923.  
  924.  
  925.  
  926.  
  927.  
  928.  
  929.  
  930.  
  931.  
  932.          Expressions - Conditional Expressions
  933.  
  934.          The AWK conditional expression has the form:
  935.  
  936.                          exp1 ? exp2 : exp3
  937.  
  938.          Exp1 is evaluated and if the result of it is TRUE (nonzero or
  939.          nonNUL) the value of the conditional expression is the value
  940.          of exp2.  If exp1 is FALSE then the value of the conditional
  941.          expression is the value of exp3.  Consider the following AWK
  942.          program fragment:
  943.  
  944.               END       {
  945.                             print tot, "file" tot == 1 ? "" : "s",
  946.                                        "read"
  947.                         }
  948.  
  949.          Presumably the variable "tot" was calculated during the
  950.          course of the program and represents the number of files
  951.          read.  The END action intends to print out this number.  We
  952.          make use of a conditional statement in this action to make
  953.          the word "file" singular if there was only one file read,
  954.          otherwise we make it plural by adding an "s".  Notice that we
  955.          use the string concatenation operator to append the "s" to
  956.          the literal "file" during printing to avoid having a field
  957.          separator placed between them.
  958.  
  959.          Expressions - Relational Expressions
  960.  
  961.          Relational expressions consist of expressions formed using
  962.          the AWK comparison operators.  These expressions have either
  963.          a TRUE (1) or FALSE (0) value.  Following are the comparison
  964.          operators supported by AWK:
  965.  
  966.             Operator          Meaning               Example
  967.  
  968.               <          Less than                  x < y
  969.               <=         Less than or equal to      x <= y
  970.               ==         Equal to                   x == y
  971.               !=         Not Equal to               x != y
  972.               >=         Greater than or equal to   x >= y
  973.               >          Greater than               x > y
  974.               ~          Is matched by              x ~ y
  975.               !~         Is not matched by          x !~ y
  976.  
  977.          Relational expressions may be combined by using the logical
  978.          operators && (AND), || (OR), and ! (NOT).
  979.  
  980.          Expressions - Builtin Functions
  981.  
  982.          The functions built into AWK may be divided into two
  983.          categories: arithmetic and string.  The following tables list
  984.          the available functions in each category.  The notation used
  985.  
  986.  
  987.  
  988.                           gAWK Documentation - Page 15
  989.  
  990.  
  991.  
  992.  
  993.  
  994.  
  995.  
  996.  
  997.          to represent the type of function arguments is:
  998.  
  999.                        x, y     ==>  Numbers
  1000.                        s, t     ==>  Strings
  1001.                        r        ==>  Regular Expression
  1002.                        a        ==>  AWK array variable
  1003.  
  1004.                           Arithmetic Builtin Functions
  1005.  
  1006.               Function             Value Returned
  1007.  
  1008.               atan2(x,y)    arctangent of x/y
  1009.               cos(x)        cosine of x, with x in radians
  1010.               exp(x)        exponential function of x, e ^ x
  1011.               int(x)        integer part of x
  1012.               log(x)        natural (base e) logarithm of x
  1013.               rand()        random number n, where 0 <= n < 1
  1014.               sin(x)        sine of x, with x in radians
  1015.               sqrt(x)       square root of x
  1016.               srand(x)      seed random number generator with x
  1017.  
  1018.                             String Builtin Functions
  1019.  
  1020.               gsub(r,s)     substitute s for r globally in $0, return
  1021.                             the number of substitutions made
  1022.               gsub(r,s,t)   substitute s for r globally in string t,
  1023.                             return the number of substitutions made
  1024.               index(s,t)    return first position of string t in
  1025.                             string s or 0 if t is not present
  1026.               length(s)     return the number of characters in s
  1027.               lower(s)      return string s with all upper case
  1028.                             letters converted to lower case
  1029.               match(s,r)    test if string s contains a substring
  1030.                             matched by regular expression r, return
  1031.                             index of match or 0 if none; sets builtin
  1032.                             variables RSTART and RLENGTH
  1033.               reverse(s)    return the string s reversed
  1034.               split(s,a)    split string s into array a on FS, return
  1035.                             number of fields split
  1036.               split(s,a,r)  split string s into array a on regular
  1037.                             expression r, return number of fields
  1038.               sprintf(f,exp,...) similar to the C sprintf function.
  1039.                             string f is a format specifier and the
  1040.                             expression list is used to "fill in" the
  1041.                             % placeholders.  the return value is the
  1042.                             resultant string
  1043.               sub(r,s)      substitute s for the leftmost longest
  1044.                             substring of $0 matched by r, return the
  1045.                             number of substitutions made (0 or 1)
  1046.               sub(r,s,t)    substitute s for the leftmost longest
  1047.                             substring of t matched by r, return the
  1048.                             number of substitutions made (0 or 1)
  1049.               substr(s,x)   return the suffix of s starting at
  1050.                             position x
  1051.  
  1052.  
  1053.  
  1054.                           gAWK Documentation - Page 16
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060.  
  1061.  
  1062.  
  1063.               substr(s,x,y) return substring of s starting at position
  1064.                             x for length y
  1065.               system(s)     invoke an operating system command shell
  1066.                             and execute string s as a command
  1067.               upper(s)      return string s with all lower case
  1068.                             letters converted to upper case
  1069.  
  1070.          Expressions - User Defined Functions
  1071.  
  1072.          User defined functions are not supported in this version of
  1073.          AWK.  Support for this feature is currently under
  1074.          construction and will be available in the next release of the
  1075.          software.
  1076.  
  1077.          Statements
  1078.  
  1079.          The AWK statements define the actions to be performed upon
  1080.          variables and expressions.  The available statements are very
  1081.          "C like" in both syntax and semantics.  The types of
  1082.          statements supported are listed in the introduction to the
  1083.          ACTIONS section.  AWK statements may be terminated by a semi-
  1084.          colon, however, this is only required if more than one
  1085.          statement appears on a single line.  For example:
  1086.  
  1087.               BEGIN       { FS = "\t";  OFS = ","; }
  1088.  
  1089.          In this example the semi-colon following the first assignment
  1090.          statement is required, however the second (or last) semi-
  1091.          colon may be omitted.
  1092.  
  1093.          We will now take a closer look at each of these.
  1094.  
  1095.          Statements - print
  1096.  
  1097.          The "print" statement is used to produce simple output from
  1098.          one or more expressions.  Each expression to be printed is
  1099.          separated by a comma.  If desired, the expression list may be
  1100.          surrounded by parentheses.  Each comma separated expression
  1101.          is printed as an output field.  Fields in the output record
  1102.          are separated by the value contained in the OFS builtin
  1103.          variable.  The last expression in the print statement is
  1104.          terminated by the "record separator" value contained in the
  1105.          ORS builtin variable.  String expressions are converted for
  1106.          output via the "%s" format specifier.  Numeric expressions
  1107.          are converted for output by using the format specifier
  1108.          contained in the OFMT builtin variable which defaults to
  1109.          "%.6g".  This value can be changed by the program to alter
  1110.          the format of numeric fields.
  1111.  
  1112.          The following example uses the "print" statement to process a
  1113.          comma delimited input file containing five fields while
  1114.          exchanging the positions of the second and third fields:
  1115.  
  1116.  
  1117.  
  1118.  
  1119.  
  1120.                           gAWK Documentation - Page 17
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126.  
  1127.  
  1128.  
  1129.               BEGIN        { FS = OFS = "," }
  1130.  
  1131.                            { print($1, $3, $2, $4, $5) }
  1132.  
  1133.          The output of the print statement will be directed to the
  1134.          standard output device (stdout) by default.  The program may
  1135.          over-ride this default by use of the AWK redirection operator
  1136.          to place the output in a file or on a printer.
  1137.  
  1138.               print "This will be written to file XYZ.DAT" >"XYZ.DAT"
  1139.  
  1140.               outfile = "XYZ.DAT"
  1141.               print "This will be written to file XYZ.DAT" >outfile
  1142.  
  1143.               print "This will go to the printer" >"PRN"
  1144.  
  1145.          Statements - printf
  1146.  
  1147.          The "printf" statement in AWK is very similar to its
  1148.          counterpart in the 'C' language.  The first parameter of the
  1149.          printf statement is a string containing "format specifiers"
  1150.          which determine how the remaining parameters are formatted
  1151.          and printed.  The format string is always required,
  1152.          additional parameters are required based on the number of
  1153.          specifiers in the format string.
  1154.  
  1155.          A format specifier has the following parts:
  1156.  
  1157.                %[-][0][width][.prec]char
  1158.                ! !  !    !      !    +----> printf format ctrl char
  1159.                ! !  !    !      +---------> max string width or number
  1160.                ! !  !    !                  digits to right of decimal
  1161.                ! !  !    +----------------> minimum width for field
  1162.                ! !  +---------------------> pad with leading zeros
  1163.                ! +------------------------> left justify result
  1164.                +--------------------------> format string specifier
  1165.  
  1166.          Items within square brackets ([ ]) are optional.  The
  1167.          following table lists the valid printf format control
  1168.          characters:
  1169.  
  1170.               Character          PRINTF Expression
  1171.  
  1172.                   c            ASCII character
  1173.                   d            decimal integer
  1174.                   e            [-]d.ddddddE[+-]dd
  1175.                   f            [-]ddd.dddddd
  1176.                   g            e or f format whichever is shorter
  1177.                   o            unsigned octal number
  1178.                   s            string
  1179.                   x            unsigned hexidecimal number
  1180.                   %            literal % character
  1181.  
  1182.          As is the case with the "print" statement the output of the
  1183.  
  1184.  
  1185.  
  1186.                           gAWK Documentation - Page 18
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192.  
  1193.  
  1194.  
  1195.          "printf" statement may be redirected via the AWK redirection
  1196.          operator (>).  One difference from the "print" statement is
  1197.          that the "printf" statement requires the programmer to fully
  1198.          specify all field and record delimiters.  The OFS and ORS
  1199.          builtin variables are not used with "printf" and must be
  1200.          supplied in the format string if so desired.
  1201.  
  1202.          Statements - if
  1203.  
  1204.          The AWK "if" statement is implemented in the same manner as
  1205.          is found in the 'C' language.  The basic format is as
  1206.          follows:
  1207.  
  1208.                         if (expression)
  1209.                             statement1
  1210.                         else
  1211.                             statement2
  1212.  
  1213.          If the expression in TRUE statement1 is executed otherwise
  1214.          statement2 is executed.  The "else" portion is optional and
  1215.          need not be coded if there is not alternative action to take
  1216.          when "expression" is FALSE.  Both statement1 and statement2
  1217.          may be replaced by several statements if the statements are
  1218.          enclosed within curly braces:
  1219.  
  1220.                         if ($1 == "Jones")
  1221.                         {
  1222.                             $2 = "Common Name"
  1223.                             jones_cnt++
  1224.                         }
  1225.                         else
  1226.                             $2 = "Uncommon Name"
  1227.  
  1228.          Statements - while
  1229.  
  1230.          The AWK "while" statement executes a statement or block of
  1231.          statements enclosed within curly braces as long as the
  1232.          supplied expression is TRUE.  If the expression starts off
  1233.          being FALSE the statements are never executed.  Following is
  1234.          the format of the "while" statement:
  1235.  
  1236.                      while (expression) statement
  1237.  
  1238.          Following is an example:
  1239.  
  1240.                      i = NF
  1241.                      while (i > 0)
  1242.                      {
  1243.                          print $i
  1244.                          --i
  1245.                      }
  1246.  
  1247.          Statements - do
  1248.  
  1249.  
  1250.  
  1251.  
  1252.                           gAWK Documentation - Page 19
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258.  
  1259.  
  1260.  
  1261.          The "do" statement is similar to the "while" statement with
  1262.          the exception that the test of the expression is made after
  1263.          the statement has been executed.  For this reason the
  1264.          statement(s) within a "do" loop will always be executed at
  1265.          least one time even if the expression starts off being FALSE.
  1266.          The format of the "do" statement is:
  1267.  
  1268.                      do statement while (expression)
  1269.  
  1270.          Following is an example:
  1271.  
  1272.                      i = NF
  1273.                      do
  1274.                      {
  1275.                          print $i
  1276.                          --i
  1277.                      } while (i > 0)
  1278.  
  1279.          In this example, what will happen if NF == 0?
  1280.  
  1281.          Statements - for
  1282.  
  1283.          The AWK "for" statement has two forms, one which should be
  1284.          familiar to 'C' programmers and one which should be familiar
  1285.          to SNOBOL programmers.  The SNOBOL version allows looping
  1286.          through all the elements of an AWK array and we will defer
  1287.          discussion of this variant until we talk about associative
  1288.          arrays in AWK.
  1289.  
  1290.          The 'C' version of "for" has the following format:
  1291.  
  1292.                      for (exp1; exp2; exp3) statement
  1293.  
  1294.          This version of the "for" statement can best be described via
  1295.          the programming constructs from which it is comprised.
  1296.          Following is AWK language code which implements a "for"
  1297.          statement using constructs we have already covered:
  1298.  
  1299.                       exp1
  1300.                       while (exp2)
  1301.                       {
  1302.                           statement
  1303.                           exp3
  1304.                       }
  1305.  
  1306.          In verbiage this means that exp1 is executed at the start of
  1307.          the loop one time.  Then while exp2 is TRUE the statement
  1308.          associated with the "for" is executed followed by exp3.  This
  1309.          loop continues until exp2 is FALSE.  Note that if exp2 is
  1310.          FALSE at the beginning of the loop it is never executed.
  1311.          Following is an example of this type of "for" statement:
  1312.  
  1313.                       for (i = NF; i > 0; --i)
  1314.                           print $i
  1315.  
  1316.  
  1317.  
  1318.                           gAWK Documentation - Page 20
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324.  
  1325.  
  1326.  
  1327.          Looking back at our example in the discussion of the "while"
  1328.          statement you will note that this example performs the
  1329.          identical function.
  1330.  
  1331.          Statements - delete
  1332.  
  1333.          The "delete" statement removes an element of an associative
  1334.          array from memory.  Again, we will defer discussion of this
  1335.          statement to the section on AWK arrays.
  1336.  
  1337.          Statements - break
  1338.  
  1339.          The AWK break statement is used to terminate one of the
  1340.          looping constructs prior to its normal termination.  Use of
  1341.          the "break" statement outside of a loop is invalid.  The
  1342.          following examples demonstrate the use of "break":
  1343.  
  1344.                       i = NF
  1345.                       while (1)
  1346.                       {
  1347.                           if (i > 0)
  1348.                               print $i
  1349.                           else
  1350.                               break
  1351.                           --i
  1352.                       }
  1353.  
  1354.                       for (i = NF; 1; --i)
  1355.                           if (i > 0)
  1356.                               print $i
  1357.                           else
  1358.                               break
  1359.  
  1360.          Statements - continue
  1361.  
  1362.          The "continue" statement in AWK, as in 'C', is used within a
  1363.          loop to immediately return to the expression evaluation
  1364.          portion of the looping statement.  In the case of a "while"
  1365.          or a "do" loop the loop expression is evaluated and the loop
  1366.          is continued or terminated based on its value.  In the case
  1367.          of a for loop, exp3 is executed and then exp2 is evaluated to
  1368.          determine if the loop should terminate.  In either case the
  1369.          remaining code in the loop is not executed during the current
  1370.          iteration.  The following example prints out all fields of a
  1371.          record which contain valid integer numbers.  The "continue"
  1372.          statement is used to skip the printing if the match for
  1373.          numeric value fails:
  1374.  
  1375.                       for (i = 1; i <= NF; ++i)
  1376.                       {
  1377.                           if ($i !~ /^[0-9]+$/)
  1378.                               continue
  1379.                           printf("%d ", $i)
  1380.                       }
  1381.  
  1382.  
  1383.  
  1384.                           gAWK Documentation - Page 21
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390.  
  1391.  
  1392.  
  1393.          Statements - next
  1394.  
  1395.          The AWK "next" statement is used to terminate the processing
  1396.          of the current input record and continue the implied input
  1397.          loop with the next record to be processed.  Recall that each
  1398.          input record is matched against every pattern in the program
  1399.          and, if TRUE, executes the corresponding action.  If a
  1400.          particular pattern decides that the program should not
  1401.          continue processing a particular record the "next" statement
  1402.          can be used to discard the current record and proceed with
  1403.          the next one.  The following example uses "next" to discard
  1404.          records that have less than five fields:
  1405.  
  1406.               NF < 5          { next }
  1407.  
  1408.               $6 == "Jones"   { print "Record", NR, "is a Jones" }
  1409.  
  1410.          Statements - exit
  1411.  
  1412.          The "exit" statement can be used within an AWK action to
  1413.          terminate processing of the program before the end of input.
  1414.          The "exit" statement will terminate the implied input loop
  1415.          and execute the END action if the program has one.  If the
  1416.          "exit" statement appears within the action associated with
  1417.          the END pattern it simply terminates the program.  The
  1418.          following program terminates processing after reading 20
  1419.          input records:
  1420.  
  1421.               NR > 20         {
  1422.                                   print "Terminating execution"
  1423.                                   exit
  1424.                               }
  1425.  
  1426.                               { print "Processing record", NR }
  1427.  
  1428.               END             { print "Done processing" }
  1429.  
  1430.          Statements - assignment
  1431.  
  1432.          The AWK assignment statement is similar to its 'C'
  1433.          counterpart.  It is used to assign a new value to a variable.
  1434.          The AWK assignment statement supports all the 'C' variations
  1435.          such as:
  1436.  
  1437.                  Operator       Format            Meaning
  1438.  
  1439.                      =          x  = y            x = y
  1440.                     +=          x += y            x = x + y
  1441.                     -=          x -= y            x = x - y
  1442.                     *=          x *= y            x = x * y
  1443.                     /=          x /= y            x = x / y
  1444.                     %=          x %= y            x = x % y
  1445.                     ^=          x ^= y            x = x ^ y
  1446.  
  1447.  
  1448.  
  1449.  
  1450.                           gAWK Documentation - Page 22
  1451.  
  1452.  
  1453.  
  1454.  
  1455.  
  1456.  
  1457.  
  1458.  
  1459.          Builtin Functions
  1460.  
  1461.          The Expressions section above presented a table of the
  1462.          functions built into AWK.  We will now examine each of these
  1463.          functions in closer detail.
  1464.  
  1465.          Builtin Functions - atan2(x, y)
  1466.  
  1467.          This function calculates the arctangent of x / y.  The return
  1468.          value is in the range -PI to PI.  The signs of both arguments
  1469.          are used to determine the quadrant of the return value.  The
  1470.          following example prints the arctangent of 1.0 and -1.0:
  1471.  
  1472.               print "Arctangent of 1 and -1 is:", atan2(-1, 1)
  1473.  
  1474.          Builtin Functions - cos(x)
  1475.  
  1476.          This function returns the cosine of its parameter x.  The
  1477.          following example displays the cosine of PI:
  1478.  
  1479.               PI = 3.14159265359
  1480.               print "Cosine of PI is:", cos(PI)
  1481.  
  1482.          Builtin Functions - exp(x)
  1483.  
  1484.          This function returns the value of e raised to the x power.
  1485.          The following prints the value of e ^ 2.
  1486.  
  1487.               print exp(2)
  1488.  
  1489.          Builtin Functions - gsub(r, s, t)
  1490.  
  1491.          The gsub() function performs a global substitution of string
  1492.          s for each match of regular expression r in string t.  If
  1493.          string t is omitted from the call $0 is used in its place.
  1494.          The regular expression supplied as r may be a literal regular
  1495.          expression or a string which is to be treated as a dynamic
  1496.          regular expression.  The function returns the number of
  1497.          substitutions made.  Following is an example:
  1498.  
  1499.               t = "It is the best time, isn't it?"
  1500.               cnt = gsub(/is/, "was", t)
  1501.               printf "Count(%d), Result(%s)\n", cnt, t
  1502.  
  1503.          This code will print the following:
  1504.  
  1505.               Count(2), Result(It was the best time, wasn't it?)
  1506.  
  1507.          Builtin Functions - index(s, t)
  1508.  
  1509.          The index() function searches the string s for the substring
  1510.          t and returns the position of the first match or zero if t is
  1511.          not a substring of s.  Following is an example:
  1512.  
  1513.  
  1514.  
  1515.  
  1516.                           gAWK Documentation - Page 23
  1517.  
  1518.  
  1519.  
  1520.  
  1521.  
  1522.  
  1523.  
  1524.  
  1525.               s = "It was the best of times"
  1526.               print index(s, "best"), index(s, "It"), index(s, "xyz")
  1527.  
  1528.          This code will produce the following output:
  1529.  
  1530.               12 1 0
  1531.  
  1532.          Builtin Functions - length(s)
  1533.  
  1534.          This function will return the length of the string s in
  1535.          characters.
  1536.  
  1537.          Builtin Functions - lower(s)
  1538.  
  1539.          The lower() function converts all upper case letters in
  1540.          string s to lower case.  It returns the converted string.
  1541.          This function is not included in Unix versions of AWK and is
  1542.          a gAWK extension.
  1543.  
  1544.               s = lower("NOW is The timE 1234")
  1545.               print s
  1546.  
  1547.          This code will produce the following output:
  1548.  
  1549.               now is the time 1234
  1550.  
  1551.          Builtin Functions - int(x)
  1552.  
  1553.          The int() function returns a numeric value which is the
  1554.          largest integer less than x.  The following examples
  1555.          demonstrate this function:
  1556.  
  1557.               print "This should print  2:", int(2.12345)
  1558.               print "This should print -5:", int(-4.5)
  1559.  
  1560.          Builtin Functions - log(x)
  1561.  
  1562.          This function returns the natural logarithm of x.  This
  1563.          function is undefined for negative values and will produce a
  1564.          run time error.
  1565.  
  1566.          Builtin Functions - match(s, r)
  1567.  
  1568.          The match() function searches string s for a match with
  1569.          regular expression r.  It returns the position of the
  1570.          beginning of the match or zero if no match occurred.  As a
  1571.          side effect it sets builtin variables RSTART and RLENGTH.
  1572.          RSTART is set to the beginning position of the match and
  1573.          RLENGTH is set to the length of the matched string.
  1574.          Following are several examples:
  1575.  
  1576.  
  1577.  
  1578.  
  1579.  
  1580.  
  1581.  
  1582.                           gAWK Documentation - Page 24
  1583.  
  1584.  
  1585.  
  1586.  
  1587.  
  1588.  
  1589.  
  1590.  
  1591.               s = "I must be kind, only to be cruel"
  1592.               t = ".*"
  1593.               print match(s, /(kind)|(be)/), RSTART, RLENGTH
  1594.               print match(s, t), RSTART, RLENGTH
  1595.               print match(s, "none"), RSTART, RLENGTH
  1596.  
  1597.          The following output is produced by this code:
  1598.  
  1599.               7 7 2
  1600.               1 1 32
  1601.               0 0 0
  1602.  
  1603.          Builtin Functions - rand()
  1604.  
  1605.          This function returns a pseudorandom number which is greater
  1606.          than or equal to zero but less than one.  Refer to the
  1607.          srand() function for information on seeding the random number
  1608.          generator.
  1609.  
  1610.          Builtin Functions - reverse(s)
  1611.  
  1612.          This function returns its argument as a string in which all
  1613.          the characters are reversed.  For example:
  1614.  
  1615.                    print reverse("ABCDEF")
  1616.  
  1617.          The above statement will produce the output FEDCBA.  The
  1618.          reverse() function is a gAWK extension and is not available
  1619.          in Unix AWK.
  1620.  
  1621.          Builtin Functions - sin(x)
  1622.  
  1623.          This function returns the sine of its argument x.  The
  1624.          following example prints the sine of PI / 2 which should be
  1625.          1.0.
  1626.  
  1627.               PI = 3.1415926535
  1628.               print "Sine of PI / 2:", sin(PI / 2)
  1629.  
  1630.          Builtin Functions - split(s, a, r)
  1631.  
  1632.          The split() function is used to split a string "s" into
  1633.          fields in array "a" based upon a regular expression "r".  The
  1634.          regular expression passed may be either a literal expression
  1635.          (/regexp/) or a dynamic expression ("regexp").  If "r" is
  1636.          omitted then the current value of the FS builtin variable is
  1637.          used.  The split() functions uses the regular expression to
  1638.          find field delimiters within the string.  It then creates an
  1639.          associative array of fields and returns the number of fields
  1640.          (or array elements) created.  For example, the following code
  1641.          will split a string delimited by commas and then print out
  1642.          each individual field in the string.
  1643.  
  1644.  
  1645.  
  1646.  
  1647.  
  1648.                           gAWK Documentation - Page 25
  1649.  
  1650.  
  1651.  
  1652.  
  1653.  
  1654.  
  1655.  
  1656.  
  1657.               str  = "Now,is the,time,for all,good,men and women"
  1658.               flds = split(str, arr, /,/)
  1659.               print "The string contains", flds, "fields"
  1660.               for (i = 1; i <= flds; ++i)
  1661.                   print "Field", i, "(" arr[i] ")"
  1662.  
  1663.          The above code should produce the following output:
  1664.  
  1665.               The string contains 6 fields
  1666.               Field 1 (Now)
  1667.               Field 2 (is the)
  1668.               Field 3 (time)
  1669.               Field 4 (for all)
  1670.               Field 5 (good)
  1671.               Field 6 (men and women)
  1672.  
  1673.          Builtin Functions - sprintf(fmt [,exp] ...)
  1674.  
  1675.          The sprintf() function is very similar to its C language
  1676.          counterpart with the exception that the AWK sprintf() returns
  1677.          its resultant string rather than being passed a pointer of a
  1678.          buffer to place it in.  The format string "fmt" is the only
  1679.          required argument and it may contain format specifiers as
  1680.          documented under the "printf" statement.  The variable number
  1681.          of "exp" arguments passed should equal the number of print
  1682.          specifiers in the format string.  The return value is the
  1683.          resultant string after applying the expression list to the
  1684.          format string as defined by the format specifiers.  Following
  1685.          is an example:
  1686.  
  1687.               x = sprintf("Current filename is %s", FILENAME)
  1688.               print "(" x ")"
  1689.  
  1690.          Builtin Functions - sqrt(x)
  1691.  
  1692.          This function returns the square root of x.  It is undefined
  1693.          for negative numbers and will produce a run time error.
  1694.  
  1695.          Builtin Functions - srand(x)
  1696.  
  1697.          The srand() function may be used to set a starting point for
  1698.          generating a series of pseudorandom numbers.  It may be
  1699.          called with or without an argument.  If an argument is passed
  1700.          that value is used to seed the random number generator.  If
  1701.          no argument is passed the random number generator is seeded
  1702.          from the current time of day.
  1703.  
  1704.          Builtin Functions - sub(r, s, t)
  1705.  
  1706.          The sub() function is similar to the gsub() function but
  1707.          makes at most one substitution.  sub() will substitute "s"
  1708.          for the leftmost substring of "t" which is matched by the
  1709.          regular expression "r".  If "t" is omitted it is assumed to
  1710.          be $0.  The sub() function returns the number of
  1711.  
  1712.  
  1713.  
  1714.                           gAWK Documentation - Page 26
  1715.  
  1716.  
  1717.  
  1718.  
  1719.  
  1720.  
  1721.  
  1722.  
  1723.          substitutions made which will be either zero or one.  The
  1724.          argument "r" may be either a literal or dynamic regular
  1725.          expression.
  1726.  
  1727.          Builtin Functions - substr(s, x, y)
  1728.  
  1729.          The substr() function returns the substring of "s" which
  1730.          begins at position "x" for a length of "y".  The length
  1731.          argument "y" may be omitted in which case substr() returns
  1732.          the substring beginning at position "x" for the remainder of
  1733.          the string.  If "x" is greater then the number of characters
  1734.          in string "s" a NUL string is returned.  Following are some
  1735.          examples and the output they produce:
  1736.  
  1737.                           STATEMENT                     OUTPUT
  1738.  
  1739.               print substr("ABCDEFGHIJK", 5)            EFGHIJK
  1740.               print substr("ABCDEFGHIJK", 5, 2)         EF
  1741.               print substr("ABCDEFGHIJK", 11, 1)        K
  1742.               print substr("ABCDEFGHIJK", 12, 1)
  1743.  
  1744.          Builtin Functions - system(s)
  1745.  
  1746.          The system() function will invoke a new command shell and
  1747.          execute the string "s" as a command under this child shell.
  1748.          The string passed may be a builtin MSDOS or OS/2 command such
  1749.          as DIR, or an external program file.  The return value of the
  1750.          function is the return code of the command executed.  The
  1751.          following example displays a sorted directory list using the
  1752.          SORT.EXE filter:
  1753.  
  1754.               BEGIN      {
  1755.                              fil = "$$$.tmp"
  1756.                              system(sprintf("dir | sort >%s", fil))
  1757.                              ARGV[1] = fil
  1758.                              ARGC    = 2
  1759.                          }
  1760.  
  1761.                          {
  1762.                              if (" " == substr($0, 1, 1))
  1763.                                  next
  1764.                              printf("%-16s %6d\n", $1 "." $2, $3
  1765.                          }
  1766.  
  1767.               END        { system(sprintf("del %s", fil)) }
  1768.  
  1769.          Builtin Functions - upper(s)
  1770.  
  1771.          The upper() function returns its argument string with all
  1772.          lower case letters converted to upper case.  This function is
  1773.          a gAWK extension and is not available under Unix AWK.
  1774.  
  1775.  
  1776.  
  1777.  
  1778.  
  1779.  
  1780.                           gAWK Documentation - Page 27
  1781.  
  1782.  
  1783.  
  1784.  
  1785.  
  1786.  
  1787.  
  1788.  
  1789.                               SPECIAL AWK FEATURES
  1790.  
  1791.          Associative Arrays
  1792.  
  1793.          As we have hinted at during discussion of various other
  1794.          features, AWK supports arrays similar to the manner in which
  1795.          SNOBOL implements them.  In AWK an array subscript is a
  1796.          string rather than a number as in most languages.  It is,
  1797.          therefore, perfectly legal in AWK to reference arr["HI"] as
  1798.          an array element.  You should also note that this is not the
  1799.          same array element as defined by arr["hi"].  Array subscripts
  1800.          which are specified as numbers are converted to strings so
  1801.          arr["22"] and arr[22] refer to the same array element.  In
  1802.          converting numbers to strings no leading zeros are added and
  1803.          since all subscript characters are significant arr["01"] and
  1804.          arr[1] do NOT refer to the same element.
  1805.  
  1806.          Multidimensional arrays in AWK are created with the same
  1807.          notation as used in most languages, i.e. arr[i, j, k],
  1808.          however, in AWK the multiple subscripts are concatenated
  1809.          together to form a single subscript.  The value of the
  1810.          builtin variable SUBSEP is placed between each subscript
  1811.          value.  If an array element is assigned a value with the
  1812.          statement arr["SUB1", "SUB2"] = "hi" it can also be
  1813.          referenced as arr["SUB1" SUBSEP "SUB2"].  The SUBSEP builtin
  1814.          variable is initialized to the octal number /034 (Ctrl-\)
  1815.          however it can be changed by the programmer to any character
  1816.          or string which will allow multidimensional array elements to
  1817.          be unique.
  1818.  
  1819.          AWK arrays are dynamically created and can be expanded or
  1820.          contracted at will.  There is no need to declare a variable
  1821.          as an array, simply assigning it values as a subscripted
  1822.          variable is sufficient.  The AWK "delete" statement may be
  1823.          used to remove elements from an array.  The format of the
  1824.          delete statement is "delete arr-element" and it is written as
  1825.          "delete arr[1]" in AWK code.  The delete statement removes
  1826.          the specified element from the array and frees all storage it
  1827.          occupied.
  1828.  
  1829.          Associative Arrays - Membership Test
  1830.  
  1831.          Since an array element can be created simply by referring to
  1832.          it by name it is not possible to test for the existence of a
  1833.          particular element via a statement of the form:
  1834.  
  1835.               if (arr[1] == "")
  1836.                    ....
  1837.  
  1838.          Since the reference to arr[1] will create it if it doesn't
  1839.          already exist and assign it the default variable value of a
  1840.          NUL string the above statement is unconditionally true.  A
  1841.          special format of the if statement exists within AWK for the
  1842.          purpose of testing an array element for existence:
  1843.  
  1844.  
  1845.  
  1846.                           gAWK Documentation - Page 28
  1847.  
  1848.  
  1849.  
  1850.  
  1851.  
  1852.  
  1853.  
  1854.  
  1855.               if ("1" in arr)
  1856.                   ....
  1857.  
  1858.          In the above example if the array element arr["1"] exists the
  1859.          statement will be TRUE otherwise it will be FALSE.  If the
  1860.          element doesn't exist it will not be created by this
  1861.          statement.  The membership test can be used to test for
  1862.          members of multidimensional arrays by using the following
  1863.          format:
  1864.  
  1865.               if ((i, j) in arr)
  1866.                   ....
  1867.  
  1868.          Associative Arrays - Element Enumeration
  1869.  
  1870.          An array in most conventional languages is pre-defined to the
  1871.          compiler or interpreter and restricted to certain bounds.  In
  1872.          general, either 0 or 1 is implicitly defined as the lower
  1873.          bound and the upper bound is programmer defined.  In either
  1874.          case the subscript value for all elements is known as the
  1875.          range of numbers from the lower to the upper bound.  In AWK
  1876.          this is not the case as the set of array subscripts in use is
  1877.          disjoint.  AWK provides a variation of the "for" statement
  1878.          which allows all active subscripts within an array to be
  1879.          enumerated.  The format of this statement is:
  1880.  
  1881.               for (sub in arr)
  1882.                   ....
  1883.  
  1884.          This loop will be executed once for each element of the array
  1885.          "arr".  On each iteration of the loop the scalar variable
  1886.          "sub" will be assigned the value of the current array
  1887.          subscript.  Therefore, the code:
  1888.  
  1889.               for (sub in arr)
  1890.                   print "arr[" sub "]=", arr[sub]
  1891.  
  1892.          will print out all the elements of array "arr".
  1893.  
  1894.          This version of the "for" statement does not support
  1895.          multidimensional array notation for subscripts, however, it
  1896.          can be used on multidimensional arrays since, as previously
  1897.          mentioned, they are really stored as single dimension arrays
  1898.          with concatenated subscript values.  If the individual
  1899.          subscript elements need to be accessed that can be obtained
  1900.          via the split() builtin function.  For example:
  1901.  
  1902.               arr[1, 1] = 1; arr[1, 2] = 2; arr[1, 3] = 3
  1903.               for (i in arr)
  1904.               {
  1905.                   split(i, x, SUBSEP)
  1906.                   print "arr[" x[1] "," x[2] "," x[3] "]=",
  1907.                         arr[x[1], x[2], x[3]]
  1908.               }
  1909.  
  1910.  
  1911.  
  1912.                           gAWK Documentation - Page 29
  1913.  
  1914.  
  1915.  
  1916.  
  1917.  
  1918.  
  1919.  
  1920.  
  1921.          Associative Arrays - Example
  1922.  
  1923.          We will leave this discussion of AWK arrays by presenting an
  1924.          example of there use which, I believe, will demonstrate how
  1925.          powerful they can be.  The following short AWK program will
  1926.          read any number of text files specified on the command line
  1927.          and produce a report of the number of lines in each file:
  1928.  
  1929.                       { cnt[FILENAME]++ }
  1930.  
  1931.               END     {
  1932.                           for (i in cnt)
  1933.                           {
  1934.                               printf("File %-16s %5d line%s\n",
  1935.                                      i, cnt[i],
  1936.                                      cnt[i] == 1 ? "" : "s")
  1937.                           }
  1938.                       }
  1939.  
  1940.          Please note that the majority of the code in this example is
  1941.          concerned with displaying the output of the program.  The
  1942.          actual work of counting the lines within each file is
  1943.          performed with a single AWK statement.
  1944.  
  1945.  
  1946.                                    REFERENCES
  1947.  
  1948.          Aho, Alfred V., Brian W. Kernighan, and Peter J. Weinberger
  1949.          [1988] "The AWK Programming Language", Addision-Wesley
  1950.          Publishing Company, 1988.
  1951.  
  1952.          Downs, Brian W. [1989], "AWK Comes of Age, Part 1", Unix
  1953.          World, January 1989, pp 103-109.
  1954.  
  1955.          Downs, Brian W. [1989], "AWK Comes of Age, Part 2", Unix
  1956.          World, February 1989, pp 115-122.
  1957.  
  1958.          Kernighan, Brian W., and Rob Pike [1984], "The UNIX
  1959.          Programming Environment", Prentice-Hall, 1984.
  1960.  
  1961.          Tare, R. S. [1987], "UNIX Utilities", McGraw-Hill, 1987.
  1962.  
  1963.                                     CREDITS
  1964.  
  1965.          This package was originally developed in cooperation with the
  1966.          GNU Project headed by Dr. Richard Stallman.  It has been
  1967.          enhanced and modified by numerous authors and is distributed
  1968.          under the guidelines of the Free Software Foundation.  These
  1969.          guidelines may be found in a separate file named "COPYING".
  1970.  
  1971.          To the best of my knowledge all of the authors of this
  1972.          package agree with this distribution policy and fully support
  1973.          the free distribution of software in source code form.
  1974.  
  1975.  
  1976.  
  1977.  
  1978.                           gAWK Documentation - Page 30
  1979.  
  1980.  
  1981.  
  1982.  
  1983.  
  1984.  
  1985.  
  1986.  
  1987.          The original version of gAWK was developed by Paul Rubin in
  1988.          1986 and released to the GNU Project.
  1989.  
  1990.          The original version of the gAWK builtin functions was
  1991.          written by Jay Fenlason in 1986.
  1992.  
  1993.          The enhancements for range patterns and various other fixes
  1994.          were made by a programmer identified only as "jfw".
  1995.  
  1996.          Numerous fixes were applied by a programmer identified only
  1997.          as "JF".
  1998.  
  1999.          All of the newer features of AWK were implemented by Bob
  2000.          Withers.  The code was also ported to both MSDOS and OS/2
  2001.          systems under Microsoft C V5.10.
  2002.  
  2003.          The AWK grammer for this release was processed by the PD
  2004.          version of YACC which was originally developed by J van
  2005.          Katwijk of The Delft University of Technology, Delft, The
  2006.          Netherlands.  This code has been extensively modified and
  2007.          ported by Bob Denny, Scott Guthery, and Bob Withers among
  2008.          others.
  2009.  
  2010.          There are, I'm sure, other hands through which this code has
  2011.          passed on its way to me but I have not been able to identify
  2012.          them.  To those programmers I apologize for the omission and
  2013.          express thanks for their efforts.
  2014.  
  2015.  
  2016.  
  2017.  
  2018.  
  2019.  
  2020.  
  2021.  
  2022.  
  2023.  
  2024.  
  2025.  
  2026.  
  2027.  
  2028.  
  2029.  
  2030.  
  2031.  
  2032.  
  2033.  
  2034.  
  2035.  
  2036.  
  2037.  
  2038.  
  2039.  
  2040.  
  2041.  
  2042.  
  2043.  
  2044.                           gAWK Documentation - Page 31
  2045.  
  2046.  
  2047.